/*
 * chatter_err_log.c
 * 几个api的实现....
 */

#include "chatter_err_log.h"

#include <time.h>
#include <pthread.h>		//use in write file

#define LOG_BUFFER 256

extern pthread_mutex_t write_log_mutex ;

void write_log(const char logtype, const char *format, ...)
{

	char		buf[LOG_BUFFER];
	va_list		arg;
	memset(buf, 0, LOG_BUFFER);

	switch(logtype & 126)
	{//126 is a MASK[0111 1110]
		case 2:
			strcat(buf, "[--]\t");
			break;
		case 4:
			strcat(buf, "[WW]\t");
			break;
		case 8:
			strcat(buf, "[EE]\t");
			break;
		default:
			fprintf(stderr, "warning:wrong arg in write_log\n");
			return;
	}

	time_t t = time(NULL);
	strcat(buf, asctime(localtime(&t)));
	buf[strlen(buf) -1 ] = '\t';	//in practise , the last byte is not what we want:(\n

	switch(logtype & 241)
	{//241 IS ANOTHER MASK[1111 0001]
		case 0:
			strcat(buf, "NOMARL\t");
			break;
		case 128:
			strcat(buf, "SYSTEM\t");
			break;
		default:
			fprintf(stderr, "warning:wrong arg in write_log\n");
			return;
	}

	/*** convert the args to string ***/
	va_start(arg, format);
	vsnprintf(strchr(buf, '\0'), (LOG_BUFFER - strlen(buf) -1), format, arg);
	va_end(arg);

	buf[strlen(buf) < (LOG_BUFFER-2) ? strlen(buf) : LOG_BUFFER -2] = '\n';

	/***** lock the logfile *****/
	pthread_mutex_lock( &write_log_mutex );

	FILE *fptr = fopen("server.log", "a");
	if(fptr == NULL)
	{
		fprintf(stderr, "can't open file logfle:%m\n" );
		exit(1);	
	}

	if(fputs(buf, fptr) == EOF)
		fprintf(stderr, "error write log\n");

	fclose(fptr);

	/***** unlock the logfile ****/
	pthread_mutex_unlock( &write_log_mutex );
}

#undef LOG_BUFFER

void err_msg(const char *format, ...)
{
	va_list arg;

	va_start(arg, format);
	vfprintf(stderr, format, arg);
	va_end(arg);
	return;
}

void err_exit(const char *format, ...)
{
	va_list arg;

	va_start(arg, format);
	vfprintf(stderr, format, arg);
	va_end(arg);
	exit(1);
}
